<template>
  <div class="list-table">
    <div class="area-header">
      <span class="area-header-title">{{ $t(title) }}</span>
    </div>
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item
        v-for="item in queryColumn"
        :key="item.id"
        :label="item.label"
        :prop="item.name"
      >
        <el-input
          v-model="queryParams[item.name]"
          :placeholder="item.label"
          clearable
          @keyup.enter.native="queryHandle"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t('搜索') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('重置') }}</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="addHandle"
        >{{ $t('新增') }}</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="dataList" border>
      <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
        <template slot-scope="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        v-for="item in listColumn"
        :key="item.id"
        :label="item.label"
        :prop="item.name"
        v-bind="item"
        align="center"
      >
        <template slot-scope="scope">
          <span v-if="item.tagName === 'el-select'">{{ getSelectLabel(scope.row[scope.column.property]) }}</span>
          <span v-else>{{ scope.row[scope.column.property] }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="formBase.enableProcess === 'Y'" :label="$t('审批状态')" show-overflow-tooltip align="center" width="120">
        <template slot-scope="scope">
          <ProcessStatus :status="scope.row.actStatus" :act-id="scope.row.actId" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <template v-if="formBase.enableProcess === 'Y'">
            <ListBtn :bus-data="scope.row" />
          </template>
          <template v-else>
            <el-button
              size="small"
              type="text"
              icon="el-icon-edit"
              @click="updateHandle(scope.row)"
            >{{ $t('修改') }}</el-button>
            <el-button
              size="small"
              type="text"
              icon="el-icon-delete"
              @click="deleteHandle(scope.row)"
            >{{ $t('删除') }}</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改单基本信息对话框 -->
    <el-dialog v-loading="formOpenLoading" :title="$t(title)" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="magicalForm" append-to-body>
      <Form ref="form" :form-id-prop="formId" />
    </el-dialog>
  </div>
</template>

<script>
import { findShowColumn } from '@/api/dev/form/column/formTableColumn'
import { deleteForm, exportFormBase, getFormBase, formList, saveFormData, getByFormIdAndDataId, findListByFormId } from '@/api/dev/form/base/formBase'
import { getToken } from '@/utils/auth'
import Form from '@/views/dev/form/base/form'

export default {
  components: { Form },
  data() {
    return {
      // 遮罩层
      loading: true,
      formLoading: true,
      formOpenLoading: window.loading || true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      formOpen: false,
      // 列表数据
      dataList: [],
      fileList: [],
      // 是否隐藏保存按钮
      btnHide: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 行信息
      rowData: {},
      // 表单基本信息
      formBase: {},
      formId: this.$route.query.formId,
      queryColumn: [],
      // 下拉选项
      selectOptions: [],
      listColumn: [],
      formUrl: '/magicalcoder/magicalcoder.html'
    }
  },
  watch: {
    '$route': {
      handler(val) {
        this.formId = val.query.formId || ''
        if (this.formId) {
          this.initLoad()
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
  },
  mounted() {
    window.getByFormId = (id) => {
      return getByFormIdAndDataId({ formId: this.formId, dataId: id })
    }
    window.token = getToken()
    window.baseUrl = process.env.VUE_APP_BASE_API
    window.currentLoginUserId = this.$store.state.user.userId
    window.userTree = this.$store.state.user.userTree
    findListByFormId(this.formId).then(res => {
      this.selectOptions = res.data
    })
  },
  methods: {
    initLoad() {
      this.formLoading = true
      getFormBase(this.formId).then(res => {
        this.formBase = res.data
        if (this.formBase.joinField && this.formBase.joinField !== '') {
          this.queryParams.sourceId = this.$route.query[this.formBase.joinField]
        }
        this.getList()
        this.title = res.data.name
        findShowColumn(res.data.uniqueKey).then(res => {
          this.queryColumn = res.data.searchColumnList
          this.listColumn = res.data.showColumnList
          this.formLoading = false
        })
      })
    },
    /** 查询单基本信息列表 */
    getList() {
      this.loading = true
      formList({ formId: this.formId, params: this.queryParams }).then(res => {
        this.dataList = res.rows
        this.total = res.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    queryHandle() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryHandle()
    },
    /** 新增按钮操作 */
    addHandle() {
      this.formOpen = true
      this.$nextTick(() => {
        this.fileList = []
        this.dataId = undefined
        this.$refs.form.init({ formId: this.$route.query.formId, id: undefined })
      })
    },
    /** 修改按钮操作 */
    updateHandle(row) {
      this.formOpen = true
      this.$nextTick(() => {
        this.dataId = row.id
        this.$refs.form.init({ formId: this.$route.query.formId, id: this.dataId })
        this.getByFormId(row.id)
      })
    },
    getByFormId(id) {
      getByFormIdAndDataId({ formId: this.formId, dataId: id }).then(res => {
        this.rowData = res.data
        this.fileList = res.data.fileList
      })
    },
    /** 删除按钮操作 */
    deleteHandle(row) {
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(() => {
        return deleteForm({ formId: this.formId, dataId: row.id })
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('删除成功'))
      }).catch(function() {
      })
    },
    /** 导出按钮操作 */
    exportHandle() {
      const queryParams = this.queryParams
      this.$confirm(this.$t('是否确认导出数据项?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return exportFormBase(queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    },
    // 取消按钮
    cancel() {
      this.formOpen = false
    },
    reset() {
      this.formOpen = false
      this.getList()
    },
    submitForm(type) {
      this.formOpenLoading = true
      const data = {
        formId: this.formId,
        dataId: this.dataId,
        data: this.$refs.iframe.contentWindow.getData(),
        fileList: this.fileList
      }
      saveFormData(data).then(res => {
        if (res.code === 200) {
          this.msgSuccess(this.$t('保存成功'))
          this.dataId = res.data.id
          // 点击的按钮是保存并启动流程
          if (type === 'process') {
            // 启动流程
            this.startProcess(this.dataId)
            // 点击的仅保存
          } else {
            this.msgSuccess(this.$t('保存成功'))
            // 关闭form页面
            this.cancel()
            this.formOpenLoading = false
          }
          this.getList()
        } else {
          this.msgError(res.msg)
        }
      })
    },
    getSelectLabel(value) {
      if (this.selectOptions) {
        var actions = []
        Object.keys(this.selectOptions).map((key) => {
          if (this.selectOptions[key].selectValue === ('' + value)) {
            actions.push(this.selectOptions[key].selectLabel)
            return false
          }
        })
        return actions.join('')
      } else {
        return value
      }
    }
  }
}
</script>

<style scoped>

</style>
